import React, { Component } from 'react'
import {
  Select,
  Button,
  Table,
  Modal,
  Input,
  DatePicker,
  Form,
  message,
  Tooltip,
  Space,
  Row,
  Col,
} from 'antd'
import { DownloadOutlined, EditOutlined, SwapOutlined } from '@ant-design/icons'
import 'antd/dist/antd.css'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { getDictionaryLabel } from '../../rudexRou/OperatesCookie.js'
import AdvancedSearchForm from '../../componentJsx/common/searchForm'
import '../../componentCss/component.css'
import HasPermi from '../../componentJsx/common/hasPermi'
import EditForm from '../../componentJsx/common/editForm'
import { confirmDeptByCode } from '../../utils'
import {
  queryRiskPage,
  riskDel,
  editRisk,
  exportRisk,
  exportAsync,
} from '../../api'
const { Option } = Select

class Risk extends Component {
  constructor(props) {
    super(props)
    this.state = {
      total: 0,
      pageSize: 10,
      page: 1,
      loading: false,
      isEditVisible: false, // 修改模态框状态
      isMoveVisible: false, // 移出风险区模态框状态
      isExportVisible: false, // 导出模态框状态
      confirmLoading: false, // 导出模态框状态
      dataList: [], // 表格数据
      searchParams: {},
      // 表格列配置
      columns: [
        {
          fixed: 'left',
          title: '工号',
          dataIndex: 'empNo',
          key: 'empNo',
          width: 80,
        },
        {
          fixed: 'left',
          title: '姓名',
          dataIndex: 'empName',
          key: 'empName',
          width: 80,
        },
        {
          title: '地域',
          dataIndex: 'regionName',
          key: 'regionName',
          ellipsis: true,
          width: 100,
          // render: (text) =>
          //   text ? getDictionaryLabel('addressConfig', text) : text,
        },
        {
          title: '部门BD',
          dataIndex: 'orgBdName',
          key: 'orgBdName',
          ellipsis: true,
          width: 180,
        },
        {
          title: '部门BU',
          dataIndex: 'orgBuName',
          key: 'orgBuName',
          ellipsis: true,
          width: 180,
        },
        {
          title: '部门CU',
          dataIndex: 'orgCuName',
          key: 'orgCuName',
          ellipsis: true,
          width: 180,
        },
        {
          title: '项目经理',
          dataIndex: 'projectManager',
          key: 'projectManager',
          ellipsis: true,
          width: 100,
        },
        {
          title: '风险类型',
          dataIndex: 'riskType',
          key: 'riskType',
          ellipsis: true,
          width: 100,
          render: (text) =>
            text ? getDictionaryLabel('riskSource', text) : text,
        },
        {
          title: '风险级别',
          dataIndex: 'riskLevel',
          key: 'riskLevel',
          render: (text) =>
            text ? getDictionaryLabel('riskLevel', text) : text,
          ellipsis: true,
          width: 100,
        },
        {
          title: '风险措施',
          dataIndex: 'disposeScheme',
          key: 'disposeScheme',
          render: (text) =>
            text ? getDictionaryLabel('disposeScheme', text) : text,
          ellipsis: true,
          width: 100,
        },
        {
          title: '识别人',
          dataIndex: 'discernEmpName',
          key: 'discernEmpName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '识别时间',
          dataIndex: 'discernDate',
          key: 'discernDate',
          ellipsis: true,
          width: 100,
        },
        {
          title: '风险跟踪人',
          dataIndex: 'riskDisposeEmpName',
          key: 'riskDisposeEmpName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '计划解除时间',
          dataIndex: 'planRelieveDate',
          key: 'planRelieveDate',
          ellipsis: true,
          width: 130,
        },
        {
          title: '最近修改人',
          dataIndex: 'updateUser',
          key: 'updateUser',
          ellipsis: true,
          width: 100,
        },
        {
          title: '最近修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          ellipsis: true,
          width: 160,
        },
        {
          title: '操作',
          key: 'action',
          width: 80,
          fixed: 'right',
          render: (text, record) => (
            <Space size="middle">
              <Tooltip title="编辑">
                <div style={{ width: 30 }}>
                  <HasPermi
                    bottonData={{
                      type: 'link',
                      interceptor: 'tmfs:risk:edit',
                      clickFn: () => this.editItem(record),
                      icon: <EditOutlined />,
                    }}
                  />
                </div>
              </Tooltip>
            </Space>
          ),
        },
      ],
      // 查询条件项配置
      searchForm: [
        {
          key: 1,
          type: 'input',
          name: '员工工号',
          code: 'empNo',
          maxLength: 20,
          placeholder: '请输入员工工号',
        },
        {
          key: 2,
          type: 'input',
          name: '员工姓名',
          code: 'empName',
          maxLength: 20,
          placeholder: '请输入员工姓名',
        },
        {
          key: 3,
          type: 'select',
          name: '地域',
          code: 'regionNo',
          options: getDictionaryLabel('addressConfig'),
        },
        {
          key: 4,
          type: 'cascader',
          name: '部门',
          code: 'dept',
          options: localStorage.getItem('deptList')
            ? JSON.parse(localStorage.getItem('deptList'))
            : [],
        },
        {
          key: 5,
          type: 'select',
          name: '风险来源',
          code: 'riskType',
          options: getDictionaryLabel('riskSource'),
        },
        {
          key: 6,
          type: 'select',
          name: '风险级别',
          code: 'riskLevel',
          options: getDictionaryLabel('riskLevel'),
        },
      ],
      bottonList: [
        // {
        //   interceptor: 'tmfs:risk:export',
        //   type: 'primary',
        //   clickFn: () => this.excelPort(null),
        //   icon: <DownloadOutlined />,
        //   text: '导出',
        // },
        {
          interceptor: 'tmfs:risk:del',
          clickFn: () => this.showMoveModal(null),
          icon: <SwapOutlined />,
          text: '移出风险区',
        },
      ],
      bottonListRight: [
        {
          interceptor: 'tmfs:risk:export',
          type: 'ghost',
          clickFn: () => this.excelPort(null),
          icon: <DownloadOutlined />,
          text: '导出',
        },
        // {
        //   interceptor: 'tmfs:risk:del',
        //   clickFn: () => this.showMoveModal(null),
        //   icon: <SwapOutlined />,
        //   text: '移出风险区',
        // },
      ],
      selectedRowKeys: [], // 选择行Key集合
      selectedRows: [], // 选择行集合
      selectedRow: {}, // 修改行数据
      editFormConfig: [],
      // 备选人员数据
      // empList: JSON.parse(localStorage.getItem('empList')),
    }
  }
  componentWillMount() {}
  componentDidMount() {
    this.getData()
  }
  editItem = (item) => {
    const editFormConfig = [
      {
        type: 'select',
        name: '风险级别',
        code: 'riskLevel',
        defaultVal: 'low',
        options: getDictionaryLabel('riskLevel'),
      },
      {
        type: 'select',
        name: '风险措施',
        code: 'disposeScheme',
        options: getDictionaryLabel('disposeScheme'),
      },
      {
        type: 'search',
        name: '风险跟踪人',
        code: 'riskDisposeEmpName',
        rules: [
          {
            required: true,
            message: '请输入风险跟踪人',
          },
        ],
      },
      {
        type: 'datePicker',
        name: '计划解除时间',
        code: 'planRelieveDate',
        disabledDate: (current) => {
          return current && current < moment().endOf('day')
        },
        rules: [
          {
            required: true,
            message: '请选择计划解除时间',
          },
        ],
      },
      {
        type: 'input',
        name: '风险跟踪人',
        code: 'riskDisposeEmpNo',
        hidden: true,
      },
    ]
    const updateInfo = {
      key: item.key,
      id: item.id,
      riskLevel: item.riskLevel,
      disposeScheme: item.disposeScheme,
      riskDisposeEmpName: item.riskDisposeEmpName,
      riskDisposeEmpNo: item.riskDisposeEmpNo,
      planRelieveDate: item.planRelieveDate
        ? moment(new Date(item.planRelieveDate))
        : item.planRelieveDate,
    }
    this.setState(
      {
        editFormConfig: editFormConfig,
        selectedRow: updateInfo,
        isEditVisible: true,
      },
      () => {
        //填充当前选中行的数据
        this.editFormRef.setValues(this.state.selectedRow)
        // this.modifyFormRef.current.setFieldsValue(this.state.selectedRow)
      }
    )
  }
  getData = () => {
    this.setState({ loading: true, dataList: [] })
    queryRiskPage(
      Object.assign(
        {},
        {
          currentPage: this.state.page,
          pageSize: this.state.pageSize,
        },
        this.state.searchParams
      )
    ).then((response) => {
      let dataList = []
      if (response.data.code === 200) {
        if (response.data && response.data.data) {
          const rsp = response.data.data
          dataList = rsp.list
          this.setState({ total: rsp.total })
        }
      } else {
        message.error(response.data.message || '查询数据失败!')
      }
      this.setState({
        dataList: dataList,
        loading: false,
        selectedRowKeys: [],
        selectedRows: [],
      })
    })
  }
  showMoveModal = () => {
    if (this.state.selectedRowKeys.length === 0) {
      return message.warning('请勾选需要操作的记录!')
    }
    this.setState({ isMoveVisible: true })
  }
  handleMoveOk = () => {
    this.buttonLoading(true)
    riskDel(this.state.selectedRowKeys.join(',')).then((response) => {
      if (response.data.code === 200) {
        message.success('移除数据成功!')
        this.getData()
      } else {
        message.error(response.data.message || '移除数据失败!')
      }
      this.buttonLoading(false)
      this.setState({ isMoveVisible: false })
    })
  }
  handleExportOk = () => {
    this.buttonLoading(true)
    exportAsync(this.state.searchParams).then((response) => {
      if (response.data.code === 200) {
        message.success('创建导出任务成功，请稍后在导出结果页面查看数据')
      } else {
        message.error(response.data.message || '创建导出任务失败!')
      }
      this.buttonLoading(false)
      this.setState({ isExportVisible: false })
    })
  }
  handleEditOk = () => {
    this.buttonLoading(true)
    this.editFormRef
      .validateFields()
      .then(() => {
        editRisk(
          Object.assign({}, this.editFormRef.getValues(true), {
            id: this.state.selectedRow.id,
          })
        ).then((response) => {
          if (response.data.code === 200) {
            message.success('修改数据成功!')
            this.getData()
          } else {
            message.error(response.data.message || '修改数据失败!')
          }
          this.buttonLoading(false)
          this.setState({ isEditVisible: false })
          this.editFormRef.resetFields()
        })
      })
      .catch(() => {
        this.buttonLoading(false)
      })
  }
  handleCancel = () => {
    if (this.state.isEditVisible) {
      this.editFormRef.resetFields()
    }
    this.setState({
      isMoveVisible: false,
      isEditVisible: false,
      isExportVisible: false,
    })
  }
  execSearch = (data) => {
    console.log('data', data)
    const param = {}
    const deptList = data.dept ? JSON.parse(JSON.stringify(data.dept)) : null
    delete data.dept
    const code = deptList ? deptList.pop() : []
    const item = confirmDeptByCode(code)
    if (item && item.type === 'bd') {
      param.orgBdNo = item.value
    }
    if (item && item.type === 'bu') {
      param.orgBuNo = item.value
    }
    if (item && item.type === 'cu') {
      param.orgCuNo = item.value
    }
    for (var key in data) {
      if (data[key]) {
        param[key] = data[key]
      }
    }
    this.setState({ searchParams: param, page: 1 }, () => {
      this.getData()
    })
  }
  excelPort = () => {
    if (this.state.selectedRowKeys && this.state.selectedRowKeys.length > 0) {
      exportRisk(
        `/tmfs/risk/exportByIds?ids=${this.state.selectedRowKeys.join(',')}`,
        '风险管理导出详情.xlsx'
      )
    } else {
      this.setState({ isExportVisible: true })
    }
  }
  //修改页数changePage
  changePage = (page, pageSize) => {
    this.setState({
      page,
      pageSize,
    })
    this.setState(
      {
        page,
        pageSize,
      },
      () => {
        this.getData()
      }
    )
  }
  // changeUser = (code) => {
  //   let name = ''
  //   this.state.empList.forEach((item) => {
  //     if (item.code === code) {
  //       name = item.empName
  //     }
  //   })
  //   this.modifyFormRef.current.setFieldsValue({ riskDisposeEmpName: name })
  // }
  //设置按钮加载动画开关
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag })
  }
  onRef = (ref) => {
    this.editFormRef = ref
  }
  changeUserInfo = (data) => {
    this.editFormRef.setValues({
      riskDisposeEmpName: data.empName,
      riskDisposeEmpNo: data.empNo,
    })
  }
  modifyFormRef = React.createRef() //绑定修改信息表单
  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      getCheckboxProps: (record: DataType) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    }
    const layout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    }
    return (
      <div>
        <div className="myProjectsBody">
          <div className="tabstyle">
            <div className="bigContent1" id="projectDetail">
              <AdvancedSearchForm
                execSearch={this.execSearch}
                formData={this.state.searchForm}
              />
            </div>
          </div>
          <div className="segmentationDiv"></div>
          <div className="tabstyle">
            <div className="bigContent1" id="projectDetail">
              <div className="operatingDiv">
                <Row>
                  <Col span={12}>
                    {this.state.bottonList.map((item) => (
                      <HasPermi key={item.interceptor} bottonData={item} />
                    ))}
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    {this.state.bottonListRight.map((item) => (
                      <HasPermi key={item.interceptor} bottonData={item} />
                    ))}
                  </Col>
                </Row>

                {/* <Button
                  type="primary"
                  onClick={this.excelPort}
                  icon={<DownloadOutlined />}
                >
                  导出
                </Button>
                <Button onClick={this.showMoveModal} icon={<SwapOutlined />}>
                  移出风险区
                </Button> */}
              </div>
              <div className="tableDiff">
                <Table
                  rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                  }}
                  loading={this.state.loading}
                  dataSource={this.state.dataList}
                  scroll={{ x: '100vw' }}
                  bordered
                  columns={this.state.columns}
                  rowKey={(record) => record.id}
                  pagination={{
                    total: this.state.total,
                    pageSize: this.state.pageSize,
                    current: this.state.page,
                    showSizeChanger: true,
                    onChange: this.changePage,
                    showTotal: (total) => '共 ' + total + ' 条',
                  }}
                ></Table>
              </div>
            </div>
          </div>
        </div>
        <Modal
          title="移出风险区"
          type="primary"
          okText="确认"
          cancelText="取消"
          visible={this.state.isMoveVisible}
          confirmLoading={this.state.confirmLoading}
          onOk={this.handleMoveOk}
          onCancel={this.handleCancel}
        >
          请确认是否将数据移出风险区？
        </Modal>
        <Modal
          title="确定导出数据"
          type="primary"
          okText="确认"
          cancelText="取消"
          visible={this.state.isExportVisible}
          confirmLoading={this.state.confirmLoading}
          onOk={this.handleExportOk}
          onCancel={this.handleCancel}
        >
          请确认是否根据当前查询条件导出所有数据？
        </Modal>
        <Modal
          title="修改"
          type="primary"
          okText="确认"
          cancelText="取消"
          visible={this.state.isEditVisible}
          confirmLoading={this.state.confirmLoading}
          onOk={this.handleEditOk}
          onCancel={this.handleCancel}
        >
          <EditForm
            onRef={this.onRef}
            formData={this.state.editFormConfig}
            passPermissions={true}
            changeUserInfo={this.changeUserInfo}
          />
        </Modal>
      </div>
    )
  }
}
export default Risk
